package com.zh.rent.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.zh.rent.pojo.AlipayConfig;
import com.zh.rent.pojo.Invitation;
import com.zh.rent.pojo.Setup;
import com.zh.rent.service.AccountService;
import com.zh.rent.service.AlipayService;
import com.zh.rent.service.InvitationService;
import com.zh.rent.service.SetupService;
import com.zh.rent.util.JsonResult;
import com.zh.rent.util.ToAlipay;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.*;

@Controller
@RequestMapping("/Invitation")
@Api(tags="邀请码")
public class InvitationController {
    @Autowired
    InvitationService InvitationServiceImpl;
    @Autowired
    AccountService AccountServiceImpl;

    @Autowired
    public AlipayService alipayService;
    @Autowired
    SetupService SetupServiceImpl;

    @GetMapping("/selbuyAccount")
    @ResponseBody
    @ApiOperation(value = "购买大厅显示")
    public JsonResult selbuyAccount() {
        Map<String, List<Invitation>> integerListMap = InvitationServiceImpl.selAll();
        System.out.println("%%%%%"+integerListMap);
        if(integerListMap==null){
            return JsonResult.ERROR("查找失败");
        }
        return JsonResult.OK(integerListMap);
    }



    @PostMapping("/pay")
    @ResponseBody
    @ApiOperation(value = "购买支付")
    public JsonResult pay(String AccountType,Double BuyMoney,String Voucher,Integer InvitationDays) {
        try {

            Map<String, Object> map = new HashMap<>();
            map.put("BuyMoney", BuyMoney);//金额
            map.put("InvitationDays", InvitationDays);//天数
            map.put("AccountType", AccountType);//类型
            System.out.println("111111:"+map.toString());
            //根据类型天数金额查找对应的邀请码账号id
            List<Invitation> list = InvitationServiceImpl.invDissel(map);
            System.out.println("333333"+list.toString());
            List<Integer> list1 = new ArrayList<>();
            for (Invitation invitation : list) {
                //将账号id添加进list
                list1.add(invitation.getAccountid());
            }
            System.out.println("222222"+list1.toString());
            //用账号id查找使用次数最少的账号id
            Map<String, Integer> map1 = AccountServiceImpl.accDissel(list1,InvitationDays,BuyMoney);

            map.put("Accountid", map1.get("Accountid"));
            //分配邀请码
            Invitation invitation = InvitationServiceImpl.invDis(map);
            String te=",购买";
            String s = alipayService.toAlipay(invitation.getInvitationCode(),AccountType, BuyMoney, Voucher, InvitationDays,te);
            //String s = toAlipay.toAlipay(invitation.getInvitationCode(), AccountType, BuyMoney, Voucher, InvitationDays);
            /*//对账号的邀请码数量减一，出售计数加一
            AccountServiceImpl.updateAccDis(invitation.getAccountid());
            Map<String,Object> map2 = new HashMap<>();
            map2.put("Invitationid",invitation.getInvitationid());//邀请码id
            map2.put("state",2);//状态
            map2.put("Voucher",Voucher);//凭证
            //map2.put("useTime",new Timestamp(new Date().getTime()));
            //修改邀请码信息
            int i = InvitationServiceImpl.updateInvDis(map2);*/
            System.out.println("预支付二维码："+s);
            return JsonResult.OK(s);
        } catch (Exception e) {
            return JsonResult.ERROR("购买失败:" + e.getMessage());
        }
    }
    @PostMapping("/notify")
    @ResponseBody
    public String notifys(HttpServletRequest request){
        Map<String, String> paramsMap = convertRequestParamsToMap(request);
        System.out.println("异步回调");
        System.out.println("paramsMap："+paramsMap.toString());
        String trade_status= paramsMap.get("trade_status");
        try {
            AlipayConfig alipayConfig = alipayService.selAli();
            //AlipayConfig alipayConfig = new AlipayConfig();
            boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap,
                    alipayConfig.getAlipay_public_key(),
                    alipayConfig.getCharset(),
                    alipayConfig.getSign_type());
            //无论同步异步都要验证签名
            System.out.println("异步验签结果:"+ signVerified);
            if(signVerified){
                if("TRADE_FINISHED".equals(trade_status) || "TRADE_SUCCESS".equals(trade_status)){
                    //处理自己系统的业务逻辑，如：将支付记录状态改为成功，需要返回一个字符串success告知支付宝服务器
                    System.out.println("支付成功");
                    System.out.println("out_trade_no:"+paramsMap.get("out_trade_no"));
                    System.out.println("body:"+paramsMap.get("body"));
                    //String out = paramsMap.get("out_trade_no");
                    String out=paramsMap.get("body");
                    String[] code = out.split("&");
                    System.out.println("截取："+code[0]);
                    String s= paramsMap.get("subject");
                    //String buy= s.substring(1,s.lengtsh()-1);
                    String[] str = s.split(",");

                    if(str[1].equalsIgnoreCase("续费")){
                        Integer y= 0;
                        try {
                            y = Integer.parseInt(code[0]);
                        }catch (NumberFormatException e){}
                        int i = InvitationServiceImpl.upvtRenew(y,code[1]);
                    }else {
                        //对账号的邀请码数量减一，出售计数加一
                        Invitation invitation = InvitationServiceImpl.selCodeInv(code[1]);
                        AccountServiceImpl.updateAccDis(invitation.getAccountid());
                        Map<String,Object> map2 = new HashMap<>();
                        map2.put("Invitationid",invitation.getInvitationid());//邀请码id
                        map2.put("state",2);//状态
                        map2.put("Voucher",code[0]);//凭证*//*
                        //修改邀请码信息
                        int i = InvitationServiceImpl.updateInvDis(map2);
                    }
                    return "success";
                } else {
                    //支付失败不处理业务逻辑
                    return "failure";
                }
            }else {
                //签名验证失败不处理业务逻辑
                return "failure";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "failure";
        }
    }

    @GetMapping("/return")
    @ResponseBody
    @ApiOperation(value = "支付查询")
    public String returns(String InvitationCode){
        System.out.println("同步回调");
        //AlipayConfig alipayConfig = new AlipayConfig();
        AlipayConfig alipayConfig = alipayService.selAli();
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getGatewayUrl(),
                alipayConfig.getApp_id(), alipayConfig.getMerchant_private_key(),
                "json", alipayConfig.getCharset(),
                alipayConfig.getAlipay_public_key(), alipayConfig.getSign_type());

        //设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();

        //商户订单号，商户网站订单系统中唯一订单号
        String out_trade_no = null;
        try {
            out_trade_no = new String(InvitationCode.getBytes("ISO-8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //支付宝交易号
        //String trade_no = new String(request.getParameter("WIDTQtrade_no").getBytes("ISO-8859-1"),"UTF-8");
        //请二选一设置

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\"}");

        //请求
        String result = null;
        try {
            result = alipayClient.execute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        //输出
        System.out.println(result);
        return result;
    }

    @GetMapping("/selAli")
    @ResponseBody
    @ApiOperation(value = "支付宝设置查询")
    public JsonResult selAli(){
        AlipayConfig alipayConfig = alipayService.selAli();
        return JsonResult.OK(alipayConfig);
    }
    @GetMapping("/upAlipay")
    @ResponseBody
    @ApiOperation(value = "支付宝设置修改")
    public JsonResult upAlipay(String appid,String merchantprivatekey,String alipaypublickey,
                              String gatewayUrl,String signtype){
        try {
        AlipayConfig alipayConfig= new AlipayConfig();
        alipayConfig.setApp_id(appid);
        alipayConfig.setAlipay_public_key(alipaypublickey);
        alipayConfig.setMerchant_private_key(merchantprivatekey);
        alipayConfig.setGatewayUrl(gatewayUrl);
        alipayConfig.setSign_type(signtype);
        int i = alipayService.upAlipay(alipayConfig);
        if(i==0){
            return JsonResult.ERROR("设置失败");
        }
        return JsonResult.OK("设置成功");
    } catch (Exception e) {
        return JsonResult.ERROR("发现错误:"+e.getMessage());
    }
    }

    private Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<String, String>();
        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();
        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }
        return retMap;
    }

    @GetMapping("/selVoucherInv")
    @ResponseBody
    @ApiOperation(value = "凭证查询")
    public JsonResult selVoucherInv(String Voucher) {
        try {
        //List<Invitation> invitation = invitationService.selVoucherInv(Voucher);
        List<Map<String,Object>> invitations = InvitationServiceImpl.selVoucherInvAll(Voucher);
        if(invitations!=null){
            return JsonResult.OK(invitations);
        }else {
            return JsonResult.ERROR("查找失败");
        }
        } catch (Exception e) {
            return JsonResult.ERROR("发现错误:"+e.getMessage());
        }
    }

    @PostMapping("/login")
    @ResponseBody
    @ApiOperation(value = "登录")
    public JsonResult login(String code,HttpServletRequest request) {
        try {
            //*response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        HttpSession session = request.getSession();
            Setup setup = SetupServiceImpl.setsetupAll();
            Integer time=setup.getLogmin();
            session.setMaxInactiveInterval(time*60);  //设置过期时间以秒为单位，会自动刷新
        session.setAttribute("name",code);
        Object ob=session.getAttribute("preurl");
        Invitation invitation=null;
        invitation = InvitationServiceImpl.selCodeInv(code);
        if (invitation == null) {
            return JsonResult.ERROR("登录失败邀请码不正确");
        }
            //未使用的邀请码
            if (invitation.getState() == 2) {
                Timestamp timestamp = new Timestamp(new Date().getTime());
                //修改使用状态
                InvitationServiceImpl.updateType(invitation.getInvitationid(), timestamp);
                //新用户登录
                //登录次数减一
                InvitationServiceImpl.updatelogNum(invitation.getInvitationid());
                return JsonResult.OK(0);
                //使用中的邀请码
            } else if (invitation.getState() == 1) {
                if (invitation.getLogNum() == 0) {
                    return JsonResult.ERROR("登录失败登录次数用尽");
                } else {
                    //登录次数减一
                    //int n=  iUserService.updateNum(email, code);
                    InvitationServiceImpl.updatelogNum(invitation.getInvitationid());
                }
            }else if(invitation.getState()==3){
                return JsonResult.ERROR("未购买的邀请码");
            }
        //老用户登录
        return JsonResult.OK(1);
       } catch (Exception e) {
            return JsonResult.ERROR("发现错误:"+e.getMessage());
        }
    }

    @PostMapping("/invselType")
    @ResponseBody
    @ApiOperation(value = "根据类型查找天数以及金额")
    public JsonResult invselType(String AccountType) {
        List<Map<String, Object>> list = InvitationServiceImpl.invselType(AccountType);
        if(list.size() == 0){
            return JsonResult.ERROR("查找失败");
        }
        return JsonResult.OK(list);
    }

    @PostMapping("/vtRenew")
    @ResponseBody
    @ApiOperation(value = "邀请码续费")
    public JsonResult vtRenew(String InvitationCode,Double BuyMoney,Integer InvitationDays,String AccountType) {
        try {
            String te=",续费";
            String s = alipayService.toAlipay(InvitationCode,AccountType, BuyMoney, InvitationDays.toString(), InvitationDays,te);

            return JsonResult.OK(s);
        }catch (Exception e){
            return JsonResult.ERROR("续费出现问题");
        }
    }

}
